<?php

declare(strict_types=1);

namespace App\Service;

/**
 * 店铺配送配置
 * Class ShopDeliveryConfigService
 * @package App\Service
 */
class ShopDeliveryConfigService extends BaseService
{

    const TYPE_EXPRESS = 1;
    const TYPE_OWN = 2;// 自提
    const TYPE_LOCAL = 3;// 同城配送
    const TYPE_VIRTUAL = 4; // 虚拟商品发货（不需数据库配置）
    const TYPE_USE = 5; // 待使用核销码（订座、点餐）

    const LOCAL_SEND_OWN = 2;// 自行配送
    const LOCAL_SEND_THIRD = 1;// 第三方配送

    /**
     * 获取商家配置列表
     * @param int $shop_id
     * @return array
     */
    public function getDeliveryConfigByShop(int $shop_id): array
    {
        $configs = $this->getModelInstance()->where(['delete_time' => 0, 'config_status' => 1, 'shop_id' => $shop_id])->get();
        if (empty($configs)) {
            return [];
        }
        return $configs->toArray();
    }

    /**
     * 保存配置
     * @param array $data
     * @return int
     */
    public function setDeliveryConfig(array $data): int
    {
        $instance = $this->getModelInstance()
            ->where('shop_id', '=', $data['shop_id'])
            ->where('delivery_type', '=', $data['delivery_type'])
            ->first();
        if (empty($instance)) {
            $instance = $this->getModelInstance();
        }
        foreach ($data as $fields => $val) {
            $instance->$fields = $val;
        }
        if (!$instance->save()) {
            return 0;
        }
        return (int)$instance->id;
    }

    /**
     * 获取配送配置
     * @param int $shop_id
     * @param int $type
     * @return array
     */
    public function getDeliveryConfig(int $shop_id, int $type): array
    {
        $config = $this->getModelInstance()->where(['shop_id' => $shop_id, 'delete_time' => 0, 'delivery_type' => $type])->first();
        return empty($config) ? [] : $config->toArray();
    }

    /**
     * 获取配送配置
     * @param int $shop_id
     * @param int $status
     * @return array
     */
    public function getDeliveryConfigs(int $shop_id, int $status): array
    {
        $config = $this->getModelInstance()
            ->where(['shop_id' => $shop_id, 'delete_time' => 0])
            ->where(function ($where) use ($status) {
                if (!empty($status)) {
                    // 0全部 1开启 其他：关闭
                    $where->where('config_status', '=', $status == 1 ? 1 : 0);
                }
            })
            ->get();
        return empty($config) ? [] : $config->toArray();
    }

}